var express = require('express');
var router = express.Router();
const mongoose = require("mongoose");
var url = require('url');

var User = require('../models/user');
mongoose.connect("mongodb://localhost:27017/chatUser", {
    useNewUrlParser: true
});
mongoose.Promise = Promise;
/* GET home page. */
router.get('/', function(req, res, next) {
    console.log('req.loginname ' + req.query.loginname + " " + req.query);

    res.render('index', { 'loginname': req.query.loginname });
});

router.get('/register', function(req, res) {
    req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
    req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
    res.render('register');
});

router.get('/login', function(req, res) {
    req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
    req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
    res.render('login');
});

router.post('/register', function(req, res) {
    const {
        loginname,
        password,
        confirm,
        vnum
    } = req.body;
    console.log(loginname);
    let plus = Number(vnum) === req.session.firstnum + req.session.secondnum ? true : false;
    if (plus) {
        console.log("plus: " + plus + " " + Number(vnum) + " " + req.session.firstnum + req.session.secondnum);
        saveData(new User({
            'userId': '',
            'userName': loginname,
            'userPwd': password,
            'userAge': 18
        }), res);
    } else {
        res.send({ 'str': '验证码错误!' })
    }
});


router.post('/login', function(req, res) {
    const {
        loginname,
        password,
        confirm,
        vnum
    } = req.body;
    console.log(loginname);
    let plus = Number(vnum) === req.session.firstnum + req.session.secondnum ? true : false;
    if (plus) {
        check(loginname, res);
    } else {
        res.send({ 'str': '验证码错误' });
    }
});


async function check(name, res) {
    const list = await User.find({ 'userName': name });
    if (Array.isArray(list) && list.length === 0) {
        res.send({ 'str': '当前账号不存在' });
    } else if (Array.isArray(list) && list.length > 0) {
        console.log(list);

        res.send({ "str": "登录成功", 'user': list[0] });
    }
}

async function saveData(data, res) {
    let result = '';
    // await User.remove();
    // const list = await User.find();
    // console.log();
    const list = await User.find({ 'userName': data.userName });
    if (Array.isArray(list) && list.length === 0) {
        await data.save();
        result = '注册成功!';
        console.log(result);
        res.send({ "str": result });
    } else if (Array.isArray(list) && list.length > 0) {
        result = '账号已被注册!';
        console.log(result);
        res.send({ "str": result })
    }
}

module.exports = router;